package umich.max.geolocation.clean;

import java.util.List;

import max.nlp.dal.blog.blogger.BlogAuthorProfile;
import max.nlp.dal.blog.blogger.BloggerDB;
import max.nlp.dal.blog.blogger.ParsedLocation;
import max.nlp.util.StateConverter;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;

public class ProfileCleaner {
	private BloggerDB db = BloggerDB.getInstance();

	public static void main(String[] args) {
		ProfileCleaner p = new ProfileCleaner();
		p.clean();

	}

	public void clean() {

		DBCursor itr = db.getProfileIterator();

		while (itr.hasNext()) {
			BlogAuthorProfile profile = new BlogAuthorProfile(itr.next());
			List<BasicDBObject> categoryInfo = profile.getCategoryInfo();

			for (BasicDBObject dbo : categoryInfo) {
				String category = (String) dbo.get("category");
				if (category != null) {
					String value = (String) dbo.get("value");

					if (category.equals("Location")) {
						ParsedLocation pl = parseLocation(value);
						if (pl != null) {
							profile.setParsedLocation(pl);
							db.saveProfile(profile);
						}
					}
					else if (category.equals("Gender")){
						String gender = extractGender(value);
						if (gender != null){
							profile.setparsedGender(gender);
							db.saveProfile(profile);
						}
					}
				}

			}
		}
	}

	public String extractGender(String value){
		
		if (value.toLowerCase().equals("male") || value.toLowerCase().equals("female"))
			return value;
		else
			return null;
	}
	
	public static ParsedLocation parseLocation(String location) {
		String[] parts = location.split(",");
		String city;
		String state;
		String country;
		ParsedLocation p = new ParsedLocation();
		if (parts.length == 1) {
			country = parts[0];
			p.setCountry(country);
		} else if (parts.length == 2) {
			state = str2State(parts[0]);
			country = parts[1];
			p.setState(state);
			p.setCountry(country);
		} else if (parts.length == 3) {
			city = parts[0];
			state = str2State(parts[1]);
			country = parts[2];
			p.setState(state);
			p.setCity(city);
			p.setCountry(country);

		} else {
			// System.out.println(location);
			return null;
		}
		return p;
	}

	public static String str2State(String st) {
		st = st.trim();
		String abr = StateConverter.convertToAbr(st, false);
		if (abr != null) {
			return abr;
		}
		boolean isAbr = StateConverter.isAbbr(st);
		if (isAbr)
			return st.toUpperCase();

		return st;

	}

}
